import {Component, OnInit} from '@angular/core';
import {BladeContainerBase} from '../../../../shared/blade/blade-container-base';

import {BladeContainerInterface} from '../../../../shared/blade/blade-container.interface';
import {Blade} from '../../../../shared/blade/blade.model';
import {Observable} from 'rxjs/Observable';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {SimpleChanges} from '@angular/core/core';

import {Command} from '../../../../shared/toolbar.service';
import {CircuitService} from '../../../../service/circuit.service';
import {BladeData} from '../../../../shared/blade/blade-data';
import {MyValidators} from '../../../../utils/validator/rang';
import {ColorChoicesComponent} from '../../../../shared/color-choices/color-choices.component';

import {Circuit} from '../../../../entity/circuit.model';

//风场服务，数据模型
import {FarmService} from '../../../../service/farm.service';
import {Farm} from '../../../../entity/farm.model';

//工期服务数据模型
import {PhaseService} from '../../../../service/phase.service';
import {Phase} from '../../../../entity/phase.model';

@Component({
  selector: 'app-circuit-edit',
  templateUrl: './circuit-edit.component.html',
  styleUrls: ['./circuit-edit.component.css']
})
export class CircuitEditComponent extends BladeContainerBase<Circuit> {

  public farms: Farm[] = [];       //全部风场
  public allPhases: Phase[] = [];  //全部工期
  public farmPhases: Phase[]  //风场下边的工期
  private phasesArr = [];
  public phaseStr: string;

  colorOut: {};

  constructor(
    private fb: FormBuilder,
    private circuitService: CircuitService,
    private farmService: FarmService,
    private phaseService: PhaseService) {
    super(fb);
  }

  ngOnInit(): void {
    //编辑时注册按钮和按钮命令
    if (!this.isNew) {
      this.commands = [
        new Command('save', '保存', 'fa fa-save', 'setofkey:update', (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command('reset', '重置', 'fa fa-save', 'setofkey:reset', (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ]
    }
    else {
      this.currentEntity = new Circuit(0, '', '', 0);
      this.currentEntity.phaseIds = '';
    }
    super.ngOnInit();
    this.getAllPhases();
    this.getAllFarms();
  }

  /**
   * 初始化数据
   *
   *
   * @memberof DicValueEditComponent
   */

  exeSaveChange(blade: any): void {
    this.saveChange();
  }

  canSaveChange(blade: any): boolean {
    return this.hasChange() && !this.hasError();
  }

  exeReset(blade: any): void {
    this.formGroup.reset(this.currentEntity);
    this.onChange(this.currentEntity.farmId);
    let phaseIds = this.currentEntity.phaseIds;
    this.farmPhases.forEach(phase => {
      if (phaseIds.indexOf(phase.phaseId.toString()) >= 0) {
        phase.isChecked = true;
      }
      else {
        phase.isChecked = false;
      }
    });

  }

  canReset(blade: any): boolean {
    return this.hasChange();
  }

  //获取全部风场方法；
  getAllFarms() {
    this.farmService.getFarms()
      .then(res => {
        this.farms = [...res];
        if (this.isNew) {
          if (this.parentBlade.parentEntity != null)
            this.currentEntity.farmId = (this.parentBlade.parentEntity as Farm).farmId;
          else {
            if (this.farms.length > 0)
              this.currentEntity.farmId = this.farms[0].farmId;

          }
          this.phaseService.getPhasesByfarmId(this.currentEntity.farmId).then(res => {
            this.farmPhases = [...res];
          })
          this.formPatchValue(this.currentEntity);
        }
        else {
          this.phaseService.getPhasesByfarmId(this.currentEntity.farmId).then(res => {
            this.farmPhases = [...res];
            //编辑线路时，当前线路下的工期选中
            let phasesIds = this.currentEntity.phaseIds.split(',');
            this.farmPhases.forEach(farmPhase => {
              phasesIds.forEach(phasesId => {
                if (farmPhase.phaseId == parseInt(phasesId)) {
                  farmPhase.isChecked = true;
                }
              })
            })
          });
        }
      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);
  }

  //获取所有的工期
  getAllPhases() {
    this.phaseService.getPhases()
      .then(res => {
        this.allPhases = [...res];
      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);
  }

  //根据风场id过滤当前风场下边的工期；
  getfarmPhases(id: number) {
    this.farmPhases = [];
    this.farmPhases = [...this.allPhases.filter(o => o.farmId == id)];
  }

  //change事件获取id；
  onChange(farmId: number) {
    let id: number = farmId;
    this.getfarmPhases(id);

    const errorMeg = {
      'exist': '名称已存在'
    };

    if (!this.formGroup.get('circuitName').value || this.formGroup.get('circuitName').value == this.currentEntity.circuitName) {
      return Observable.of(null);
    }
    if (this.formGroup.get('circuitName').value !== '') {
      this.circuitService.hasCircuitName(this.formGroup.get('circuitName').value, this.currentEntity.circuitId, farmId)
        .subscribe(res => {
          if (res) {
            this.formGroup.get('circuitName').setErrors(errorMeg);
          }
          else {
            //移除错误信息；
            //this.formGroup.get('circuitName').;
          }

        })
    }

    if (!this.formGroup.get('circuitCode').value || this.formGroup.get('circuitCode').value == this.currentEntity.circuitCode) {
      return Observable.of(null);
    }
    if (this.formGroup.get('circuitCode').value !== '') {
      this.circuitService.hasCircuitCode(this.formGroup.get('circuitCode').value, this.currentEntity.circuitId, farmId)
        .subscribe(res => {
          if (res) {
            this.formGroup.get('circuitCode').setErrors(errorMeg);
          }
          else {
            //移除错误信息；
            //this.formGroup.get('circuitName').;
          }
        });
    }

  }

  //获取选中工期的id；
  phaseIsChecked(check: boolean, value: Phase) {
    value.isChecked = check;
    let filter = this.farmPhases.filter(o => o.isChecked);
    if (filter) {
      let phaseIds = filter.map(o => o.phaseId);
      this.formGroup.controls['phaseIds'].setValue(phaseIds.join(','));
    }
    else {
      this.formGroup.controls['phaseIds'].setValue('')
    }
    // let idsArray = this.currentEntity.phaseIds.split(",");
    // let index = idsArray.indexOf(value.phaseId.toString());
    // if (check) {
    //     if (index < 0) {
    //         idsArray.push(value.phaseId.toString())
    //     }
    // }
    // else {
    //     if (index > -1) {
    //         idsArray.splice(index, 1);
    //     }
    // }
    // this.phaseStr = idsArray.join(',');
    // this.formGroup.controls["phaseIds"].setValue(this.phaseStr)


  }

  /**
   * 创建表单
   *
   *
   * @memberof CircuitEditComponent
   */
  createForm() {


    this.formGroup = this.fromBuider.group({
      'circuitName': [this.currentEntity.circuitName, [
        Validators.required,
        Validators.maxLength(50),
      ], (control: FormControl): any => this.circuitNameAsnyValidator(control)],
      'circuitCode': [this.currentEntity.circuitCode, [
        Validators.required,
        Validators.maxLength(20)
      ], (control: FormControl): any => this.circuitCodeAsnyValidator(control)],
      'farmId': [this.currentEntity.farmId, [
        Validators.required,
        // Validators.pattern("[0-9]{1,5}"),
        // Validators.maxLength(5),
      ]],
      'circuitLength': [this.currentEntity.circuitLength, [
        Validators.maxLength(7)
      ]],
      'phaseIds': [this.currentEntity.phaseIds, [
        Validators.required,
        // Validators.pattern("[0-9]{1,5}"),
        // Validators.maxLength(5),
      ]],
      'circuitColor': [this.currentEntity.circuitColor, [
        //Validators.required,
        Validators.pattern('^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$'),
        Validators.maxLength(7)
      ]],
      'circuitSeq': [this.currentEntity.circuitSeq, [
        Validators.maxLength(5)
      ]],
    });
  }

  /**
   * 设置表单错误对象
   *
   *
   * @memberof BladeContainerBase
   */
  setFormError(): void {
    this.formErrors = {
      'circuitName': '',
      'circuitCode': '',
      'circuitLength': '',
      'circuitSeq': '',
      'farmId': '',
      'circuitColor': '',
      'phaseIds': '',
    };
  }

  /**
   * 设置表单验证信息
   *
   *
   * @memberof BladeContainerBase
   */
  setValidationMessages(): void {

    this.validationMessages = {
      'circuitName': {
        'required': '名称不能为空。',
        'maxlength': '名称不能多于50个字符长度。',
        //'pattern': '键名称必须由字母和数字组成。',
        'exist': '线路名称已存在',
      },
      'circuitCode': {
        'required': '代码不能为空。',
        // 'pattern': '由英文、数字组成。',
        'maxlength': '键描述不能多于20个字符长度。',
        'exist': '代码名称已存在'
      },
      'circuitLength': {
        'maxlength': '键描述不能多于7个字符长度。',
      },
      'circuitSeq': {
        'maxlength': '键描述不能多于5个字符长度。',
      },
      'farmId': {
        'required': '不能为空(请选择风场)。',

      },
      'phaseIds': {
        'required': '不能为空(请选择工期)。',

      },
      'circuitColor': {

        'pattern': '颜色值只能是以#开头的数字字母。',
        'maxlength': '颜色值只能是7个字符长度。',

      }

    };
  }

  /**
   * 异步校验circuitName是否存在
   *
   * @param {FormControl} control
   * @returns {Promise<true>}
   *
   * @memberof circuitEditComponent
   */
  circuitNameAsnyValidator(control: FormControl): any {

    if (!control.value || control.value == this.currentEntity.circuitName) {
      return Observable.of(null);
    }
    return this.circuitService.hasCircuitName(control.value, this.currentEntity.circuitId, this.formGroup.get('farmId').value)
      .map(res => res ? {exist: true} : null);

  }

  circuitCodeAsnyValidator(control: FormControl): any {

    if (!control.value || control.value == this.currentEntity.circuitCode) {
      return Observable.of(null);
    }
    return this.circuitService.hasCircuitCode(control.value, this.currentEntity.circuitId, this.formGroup.get('farmId').value)
      .map(res => res ? {exist: true} : null);

  }

  /**
   * 新建一条线路
   *
   *
   * @memberof circuitEditComponent
   */
  onCreate() {
    if (!this.hasError()) {
      this.changeCurrent();
      this.circuitService.create(this.currentEntity)
        .then(res => {
          if (res) {
            let parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
          } else {
            throw new Error('数据新增失败！')
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  /**
   *
   *
   *
   * @memberof circuitEditComponent
   */
  saveChange(): any | Promise<any> | Observable<any> {
    if (this.canSaveChange(this.currentBlade)) {
      this.changeCurrent()
      return this.circuitService.update(this.currentEntity)
        .then(res => {
          if (res) {
            (this.parentBlade.bladeContainerInstance).refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
          throw new Error('数据更新失败！')

        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  changeCurrent() {
    this.bladeData.isLoading = true;
    let formValue = this.formGroup.value;
    this.currentEntity.circuitName = formValue.circuitName;
    this.currentEntity.circuitCode = formValue.circuitCode;
    this.currentEntity.circuitLength = formValue.circuitLength;
    this.currentEntity.farmId = formValue.farmId;
    this.currentEntity.phaseIds = formValue.phaseIds;
    this.currentEntity.circuitColor = formValue.circuitColor;
    this.currentEntity.circuitSeq = formValue.circuitSeq;
  }

}


// WEBPACK FOOTER //
// ./src/app/module/basic/circuit/circuit-edit/circuit-edit.component.ts
